/*
 *	Features:
 *		Order Ascending and Descending by clicking the Col Headers
 *		Toolbar Popper
 *		Delete
 *		Delete All
 *		Refresh - in GUI
 */
package text.ui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.JViewport;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import text.util.DBConnector;

public class UnusedSentencesViewer extends Viewer {

	private JTable unusedSentenceTable = null;
	private JButton buttonDelUnused;
	private JButton buttonDelAllUnused;

	public void setEnabled(boolean bEnabled) {
		if(buttonDelUnused != null) {
			buttonDelUnused.setEnabled(bEnabled);
		}
		
		if(buttonDelAllUnused != null) {
			buttonDelAllUnused.setEnabled(bEnabled);
		}
	}
	
    /**
     * Main method allows us to run as a standalone demo.
     */
    public static void main(String[] args) {
		UnusedSentencesViewer UnusedSentencesViewer = new UnusedSentencesViewer(null);
		UnusedSentencesViewer.init();
    }
    
    /**
     * UnusedSentencesViewer Constructor
     */
    public UnusedSentencesViewer(GUI gui) {
        // Set the title for this demo, and an icon used to represent this
        // demo inside the GUI app.
        super(gui, "UnusedSentencesViewer", null);
		unusedSentenceTable = createTable(createTableModel());
    }
    
	private TableModel createTableModel() {
		Vector vColumnNames = new Vector();
		vColumnNames.add("Delete");
		vColumnNames.add("Sentence #");
		vColumnNames.add("English Sentence");
		vColumnNames.add("Filipino Sentence");
		Vector vData = getData();

		TableModel unusedSentenceTableModel = new DefaultTableModel(vData, vColumnNames){
			public Class getColumnClass(int c) {
            	//hard coded: second col is an INTEGER for correct sorting of ID's
            	Class cClass = null;
            	
            	if(c == 1) {
            		try {
            			cClass = Class.forName("java.lang.Integer");
            		}catch(ClassNotFoundException e) {
            			e.printStackTrace();
            		}
            	}else {
            		cClass = getValueAt(0, c).getClass();
            	}
            	
            	return cClass;
            }
		};
		
		return unusedSentenceTableModel;
	}

	private JTable createTable(TableModel tableModel) {
		
        TableSorter sorter = new TableSorter(tableModel);
        JTable table = new JTable(sorter){
/*		    public boolean isCellEditable(int row, int col) {
		    	if(col == 0) {
		    		return true;
		    	}else {
		    		return false;
		    	}
		    }
*/		};
        sorter.setTableHeader(table.getTableHeader());

		table.getTableHeader().setReorderingAllowed(false);
		table.setDragEnabled(true);

		JScrollPane scroller = new JScrollPane();
		JViewport vp = scroller.getViewport();
		//scroller.setViewportView(table);

		JToolBar toolbarUnused = new JToolBar();
		toolbarUnused.setFloatable(false);

		buttonDelUnused = toolbarUnused.add(new DelAction(this));
		buttonDelUnused.setText("Delete");
		
		buttonDelAllUnused = toolbarUnused.add(new DelAllAction(this));
		buttonDelAllUnused.setText("Delete All");
	
		vp.add(table);
        getViewerPanel().add(toolbarUnused, BorderLayout.NORTH);
        getViewerPanel().add(scroller, BorderLayout.CENTER);
        
        return table;
	}

	public JTable getUnusedTable() {
		return unusedSentenceTable;
	}

	private Vector getData() {
		Vector vRow = new Vector();
		String	strQuery = "SELECT * FROM UnusedSentences ORDER BY sentenceID ASC";
			
		DBConnector.connect();
		ResultSet rsAll = DBConnector.select(strQuery);
		
		try{
			while(rsAll.next()) {
				Vector vCol = new Vector();
				vCol.add(new Boolean(false));
				vCol.add(new Integer(rsAll.getInt("sentenceID")));
				vCol.add(rsAll.getString("tokensEnglish").replace("->"," "));
				vCol.add(rsAll.getString("tokensFilipino").replace("->"," "));
				
				vRow.add(vCol);
			}
		}catch(SQLException e){
			e.printStackTrace();
		}

		DBConnector.close();

		if(vRow.size() == 0) {
			vRow = null;
		}
	
		return vRow;
	}


	public Vector getSelUnused() {
		Vector vSelectedID = new Vector();

		for(int i = 0; i < getUnusedTable().getRowCount(); i++) {
			//checkbox
			if(((Boolean)getUnusedTable().getValueAt(i, 0)) == Boolean.TRUE) {
				//id
				vSelectedID.add(getUnusedTable().getValueAt(i, 1));
			}
		}

		if(vSelectedID.size() == 0) {
			vSelectedID = null;
		}
	
		return vSelectedID;
	}

	public void delSelUnused(Vector vIDs) {
		for(int i = 0; i < vIDs.size(); i++) {
			delUnused(vIDs.get(i));
		}
	}

	public void delUnused(Object oID) {
		String	strQuery = "DELETE FROM UnusedSentences WHERE sentenceID = "+oID;
			
		DBConnector.connect();
		boolean bCheck = DBConnector.update(strQuery);
		
		if(!bCheck)
			System.out.println("There was a problem while deleting Unused Sentence: "+oID+".");
		else
			System.out.println("Successfully deleted Unused Sentence: "+oID+".");

		DBConnector.close();
	}
	
	public void delAllUnused() {
		String	strQuery = "DELETE FROM UnusedSentences";
			
		DBConnector.connect();
		boolean bCheck = DBConnector.update(strQuery);
		
		if(!bCheck)
			System.out.println("There was a problem while deleting the Unused Sentence.");
		else
			System.out.println("Successfully deleted ALL Unused Sentence.");

		DBConnector.close();
	}
	
	class DelAction extends AbstractAction {
		UnusedSentencesViewer UnusedSentencesViewer;
		private final String LINE_BREAK = "\n";
		private final String COMMA_SPACE = ", ";
	
		protected DelAction(UnusedSentencesViewer UnusedSentencesViewer) {
			super("DeleteAllUnused SentencesAction");
			this.UnusedSentencesViewer = UnusedSentencesViewer;
		}

		public void actionPerformed(ActionEvent e) {
			Vector vSelID = UnusedSentencesViewer.getSelUnused();
			if(vSelID == null) {
				JOptionPane.showMessageDialog(null, "There is no chunk selected. Please select one or more\nUnused Sentences by clicking the checkbox on the delete column.", null, JOptionPane.WARNING_MESSAGE);
			}else{
				//confirmation
				StringBuffer strMessage = new StringBuffer("Are you sure you want to delete the checked Unused Sentences?");
				
				int selectedIndex = JOptionPane.showConfirmDialog(null, strMessage, null, JOptionPane.YES_NO_OPTION);
				//YES
				if(selectedIndex == 0) {
					UnusedSentencesViewer.delSelUnused(vSelID);
					//refresh
					if(UnusedSentencesViewer.getGUI() != null) {
						UnusedSentencesViewer.getGUI().refreshTable(UnusedSentencesViewer);
					}
				}
			}
		}
	}

	class DelAllAction extends AbstractAction {
		UnusedSentencesViewer UnusedSentencesViewer;
	
		protected DelAllAction(UnusedSentencesViewer UnusedSentencesViewer) {
			super("DeleteUnused SentencesAction");
			this.UnusedSentencesViewer = UnusedSentencesViewer;
		}

		public void actionPerformed(ActionEvent e) {
			//confirmation
			int selectedIndex = JOptionPane.showConfirmDialog(null, "Are you sure that you want to delete ALL Unused Sentences?", null, JOptionPane.YES_NO_OPTION);
			//YES
			if(selectedIndex == 0) {
				UnusedSentencesViewer.delAllUnused();
				//refresh
				if(UnusedSentencesViewer.getGUI() != null) {
					UnusedSentencesViewer.getGUI().refreshTable(UnusedSentencesViewer);
				}
			}
		}
	}
}